package com.bnzj.core.export;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author Barry
 * @createDate 2019/10/17
 * @description
 */
public class ImportUtils {

    /**
     * //2003- 版本的excel
     */
    private final static String excel2003L = ".xls";

    /**
     * //2007+ 版本的excel
     */
    private final static String excel2007U = ".xlsx";

    /**
     * 描述：获取IO流中的数据，组装成List<List<Object>>对象
     *
     * @param in,fileName
     * @param titleNum    过滤目录 默认过滤标题首航 该参数是首航下的目录行 一般为1
     * @return
     * @throws IOException
     */
    public List<List<Object>> getBankListByExcel(Integer titleNum, InputStream in, String fileName) throws Exception {
        titleNum = ObjectUtils.isEmpty(titleNum) ? 0 : titleNum;
        //创建Excel工作薄
        Workbook work = this.getWorkbook(in, fileName);
        if (null == work) {
            throw new Exception("创建Excel工作薄为空！");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;
        List<List<Object>> list = new ArrayList<List<Object>>();
        //遍历Excel中所有的sheet
        for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = work.getSheetAt(i);
            if (sheet == null) {
                continue;
            }
            //默认从第一行开始读取数据
            for (int j = titleNum; j < sheet.getLastRowNum() + 1; j++) {
                row = sheet.getRow(j);
                if (row == null || row.getFirstCellNum() == j) {
                    continue;
                }
                //遍历所有的列
                List<Object> li = new ArrayList<Object>();
                for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                    cell = row.getCell(y);
                    li.add(this.getCellValue(cell));
                }
                list.add(li);
            }
        }
        work.close();
        return list;
    }

    /**
     * @param titleNum 忽略前n行, in 输入流, fileName 文件名称
     * @return java.util.List<java.util.List < java.lang.Object>>
     * @depict 单个shell导入
     * @auth Barry
     * @createDate 2020/3/24
     * @updateAuthOrOther
     */
    public List<List<Object>> getBankListByExcelFirstSheet(Integer titleNum, InputStream in, String fileName) throws Exception {
        //创建Excel工作薄
        Workbook work = this.getWorkbook(in, fileName);
        if (null == work) {
            throw new Exception("获取Excel工作薄为空！");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;
        List<List<Object>> list = new ArrayList<List<Object>>();
        sheet = work.getSheetAt(0);
        if (sheet == null) {
            throw new RuntimeException("sheet为空！");
        }
        for (int j = titleNum; j < sheet.getLastRowNum() + 1; j++) {
            row = sheet.getRow(j);
            if (isEmptyRow(row)) {
                continue;
            }
            //遍历所有的列
            List<Object> li = new ArrayList<Object>();
            for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                cell = row.getCell(y);
                li.add(this.getCellValue(cell));
            }
            list.add(li);
        }

        work.close();
        return list;
    }

    /**
     * 描述：根据文件后缀，自适应上传文件的版本
     *
     * @param inStr,fileName
     * @return
     * @throws Exception
     */
    public Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
        Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (excel2003L.equals(fileType)) {
            //2003-
            wb = new HSSFWorkbook(inStr);
        } else if (excel2007U.equals(fileType)) {
            //2007+
            wb = new XSSFWorkbook(inStr);
        } else {
            throw new Exception("解析的文件格式有误！");
        }
        return wb;
    }

    /**
     * 描述：对表格中数值进行格式化
     *
     * @param cell
     * @return
     */
    public Object getCellValue(Cell cell) {
    	if(null == cell) {
    		return "";
    	}
        Object value = null;
        //数字格式化
        DecimalFormat df = new DecimalFormat("0");
        //日期格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM");
        //数字格式化
        DecimalFormat df2 = new DecimalFormat("0.00");

        switch (cell.getCellType()) {
            case STRING:
                value = cell.getRichStringCellValue().getString();
                break;
            case NUMERIC:
                //org.apache.poi.ss.usermodel.BuiltinFormats
                if ("General".equals(cell.getCellStyle().getDataFormatString())) {
                    value = df.format(cell.getNumericCellValue());
                } else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
                    value = sdf.format(cell.getDateCellValue());
                } else if ("yyyy/mm".equals(cell.getCellStyle().getDataFormatString())) {
                    value = sdf1.format(cell.getDateCellValue());
                } else if("yyyy\\-mm\\-dd;@".equals(cell.getCellStyle().getDataFormatString())){
                	value = sdf.format(cell.getDateCellValue());
                } else {
                    value = df2.format(cell.getNumericCellValue());
                }
                break;
            case BOOLEAN:
                value = cell.getBooleanCellValue();
                break;
            case BLANK:
                value = "";
                break;
            case FORMULA:
                try {
                    value = cell.getStringCellValue();
                } catch (IllegalStateException e) {
                    value = String.valueOf(cell.getNumericCellValue());
                }
                break;
            default:
                break;
        }
        return value;
    }

    public static boolean isEmptyRow(Row row) {
        if (row == null || row.toString().isEmpty()) {
            return true;
        } else {
            Iterator<Cell> it = row.iterator();
            boolean isEmpty = true;
            while (it.hasNext()) {
                Cell cell = it.next();
                if (cell.getCellType() != CellType.BLANK) {
                    isEmpty = false;
                    break;
                }
            }
            return isEmpty;
        }
    }


}
